package com.blockmeta.bbs.businesslibrary.widget;

import android.content.Context;
import android.content.res.Resources;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.text.Html;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.TextPaint;
import android.text.style.RelativeSizeSpan;
import android.util.AttributeSet;
import android.util.TypedValue;

import com.blockmeta.bbs.baselibrary.R;
import com.blockmeta.bbs.businesslibrary.widget.textview.CustomFontText;
import com.blockmeta.bbs.baselibrary.base.app.BaseApp;
import com.blockmeta.bbs.baselibrary.utils.TimeUtil;
import com.blockmeta.bbs.businesslibrary.util.Format2Util;
import com.blockmeta.bbs.baselibrary.utils.FormatUtil;
import com.blockmeta.bbs.businesslibrary.websocket.AppDefine;


public class CustomTextView extends CustomFontText
{
	private int m_nDigit; // 顯示的小數位數 Format:doubleValue時可設定
	private Integer m_nFieldID; // 行情的KeyCode
	private IO_TYPE m_enIOType;
	private FORMAT m_enFormat;
	private SIGN_TYPE m_enSignType;
//	private FONT_TYPE m_enFontType;
//	private Typeface m_typeOriginal; // 預設字型
	private boolean m_bDiffColor; // 是否顯示漲跌色 資料第一碼是漲跌符號
	private boolean m_bDollarSign; // 是否顯示$
	private String m_sDollar; // 需要显示的$ 符号

	private boolean m_bDiffColorVisibility = true;
	private boolean m_bAddComma; // 數值是否加上","
	private String m_strMinSign; // Format:doubleValue longValue, 最小的顯示符號
									// Ex:K/M/B 如果設定M 則M以下的值不變更為K
	private DiffSign m_Sign = DiffSign.SIGN_EVEN;
	private boolean m_bAutoSize;
	private int m_InitSize;
	// 漲跌符號 1:上漲, 2:漲停, 3:平盤, 4:下跌, 5:跌停
	public enum DiffSign
	{
		SIGN_UP('1'), SIGN_UP_LIMIT('2'), SIGN_EVEN('3'), SIGN_DOWN('4'), SIGN_DOWN_LIMIT('5');

		private char m_value;

		DiffSign(char value)
		{
			m_value = value;
		}

		public char getValue()
		{
			return m_value;
		}

		public static DiffSign getDiffSign(char sign)
		{
			switch (sign)
			{
			case '1':
				return SIGN_UP;
			case '2':
				return SIGN_UP_LIMIT;
			case '3':
				return SIGN_EVEN;
			case '4':
				return SIGN_DOWN;
			case '5':
				return SIGN_DOWN_LIMIT;
			default:
				return SIGN_EVEN;
			}
		}

	}

	public enum IO_TYPE
	{
		NONE(0), INPUT(1), OUTPUT(2);

		private int m_value;

		IO_TYPE(int value)
		{
			m_value = value;
		}

		public int getValue()
		{
			return m_value;
		}

		public static IO_TYPE getIOType(int type)
		{
			switch (type)
			{
			case 1:
				return INPUT;
			case 2:
				return OUTPUT;
			default:
				return NONE;
			}
		}
	}

	public enum SIGN_TYPE
	{
		NONE(0), MINUS(1), BOTH(2);

		private int m_value;

		SIGN_TYPE(int value)
		{
			m_value = value;
		}

		public int getValue()
		{
			return m_value;
		}

		public static SIGN_TYPE getSignType(int type)
		{
			switch (type)
			{
			case 1:
				return MINUS;
			case 2:
				return BOTH;
			default:
				return NONE;
			}
		}
	}

	public enum FORMAT
	{
		NONE(0), RATE(1), DATE(2), TIME(3), FOREXPRICE(4), LONGVALUE(5), HTML(6), DOUBLEVALUE(7), VOLUMEVALUE(8);

		private int m_value;

		FORMAT(int value)
		{
			m_value = value;
		}

		public int getValue()
		{
			return m_value;
		}

		public static FORMAT getFormat(int format)
		{
			switch (format)
			{
			case 1:
				return RATE;
			case 2:
				return DATE;
			case 3:
				return TIME;
			case 4:
				return FOREXPRICE;
			case 5:
				return LONGVALUE;
			case 6:
				return HTML;
			case 7:
				return DOUBLEVALUE;
			case 8:
				return VOLUMEVALUE;
			default:
				return NONE;
			}
		}
	}

	public CustomTextView(Context context)
	{
		super(context);
		FONT_TYPE fontype = FONT_TYPE.getFontType(FONT_TYPE.DIN_ALTERNATE_BOLD.getValue());

		if (BaseApp.isUseDefualtFont())
			fontype = FONT_TYPE.getFontType(FONT_TYPE.NORMAL.getValue());

		setFontType(fontype);
	}

	public CustomTextView(Context context, AttributeSet attrs)
	{
		super(context, attrs);
		init(context, attrs);
	}

	public CustomTextView(Context context, AttributeSet attrs, int defStyle)
	{
		super(context, attrs, defStyle);
		init(context, attrs);
	}

	private void init(Context context, AttributeSet attrs)
	{
		TypedArray tTypeeArr = context.getTheme().obtainStyledAttributes(attrs, R.styleable.CustomTextView, 0, 0);

		m_nDigit = tTypeeArr.getInt(R.styleable.CustomTextView_digit, 0);
		m_bDiffColor = tTypeeArr.getBoolean(R.styleable.CustomTextView_diffColor, false);
		m_bAutoSize = tTypeeArr.getBoolean(R.styleable.CustomTextView_autoSize, false);
		m_bDollarSign = tTypeeArr.getBoolean(R.styleable.CustomTextView_dollarSign, false);
		m_nFieldID = (Integer) tTypeeArr.getInt(R.styleable.CustomTextView_fieldID, Short.MIN_VALUE);
		m_enIOType = IO_TYPE.getIOType(tTypeeArr.getInt(R.styleable.CustomTextView_ioType, IO_TYPE.NONE.getValue()));
		m_enSignType = SIGN_TYPE.getSignType(tTypeeArr.getInt(R.styleable.CustomTextView_signType, SIGN_TYPE.NONE.getValue()));
		m_enFormat = FORMAT.getFormat(tTypeeArr.getInt(R.styleable.CustomTextView_format, FORMAT.NONE.getValue()));
		m_bAddComma = tTypeeArr.getBoolean(R.styleable.CustomTextView_addComma, false);

		if (m_enFormat == FORMAT.LONGVALUE || m_enFormat == FORMAT.DOUBLEVALUE)
		{
			m_strMinSign = tTypeeArr.getString(R.styleable.CustomTextView_minSign);
			if (m_strMinSign == null)
				m_strMinSign = "K";
		}

		tTypeeArr.recycle();

		m_InitSize = (int) this.getTextSize();
	}


	public void setDollar(String dollar)
	{
		m_bDollarSign = true;
		m_sDollar = dollar;
	}

	public void setDigit(int digit)
	{
		m_nDigit = digit;
	}

	public void setFDTText(CharSequence text)
	{
		if (text == null)
		{
			return;
		}

		String _text = text.toString();

		try
		{
			switch (m_enSignType)
			{
			case NONE:
				if (_text.length() > 0 && _text.charAt(0) == '-')
					_text.substring(1);
				break;
			case MINUS:
				break;
			case BOTH:
				if (_text.length() > 0 && _text.charAt(0) != '-')
					_text = "+" + _text;
				break;
			}

			switch (m_enFormat)
			{
			case HTML:
				setText(Html.fromHtml(_text));
				return;
			case NONE:
				break;
			case RATE:
				if (!(_text.equals("") ||  _text.equals("-") || _text.equals("--")))
				{
					_text = _text + "%";
				}
				break;
			case DATE:
				try
				{
					int date = Integer.valueOf(_text);
					_text = String.format("%04d/%02d/%02d", TimeUtil.getYear(date), TimeUtil.getMonth(date), TimeUtil.getDay(date));
					setText(_text);
				}
				catch (Exception e1)
				{
					e1.printStackTrace();
				}
				return;
			case TIME:
				try
				{
					int time = Integer.valueOf(_text);
					_text = String.format("%02d:%02d:%02d", TimeUtil.getHour(time), TimeUtil.getMinute(time), TimeUtil.getSecond(time));
					setText(_text);
				}
				catch (Exception e1)
				{
					e1.printStackTrace();
				}
				return;
			case FOREXPRICE:
				String tText = _text.replace("-", "");
				tText = tText.replace("+", "");
				if (tText.length() > 1)
				{
					Spannable span = new SpannableString(_text);
					span.setSpan(new RelativeSizeSpan(0.8f), _text.length() - 1, _text.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
					setText(span);
				}
				else
				{
					setText(_text);
				}
				return;
			case LONGVALUE:
				try
				{
					if (!_text.equals(""))
					{
						long value = Double.valueOf(_text).longValue();
						_text = Format2Util.longToHumanReadableFormat(value, m_nDigit, m_strMinSign);
					}
				}
				catch (Exception e)
				{
					e.printStackTrace();
				}
				break;
			case DOUBLEVALUE:
				try
				{
					if (!_text.equals("") && !_text.equals("--"))
					{
						double value = Double.valueOf(_text);
						_text = Format2Util.doubleToHumanReadableFormat(value, m_nDigit);
					}
				}
				catch (Exception e)
				{
					e.printStackTrace();
				}
				break;
			case VOLUMEVALUE:
				try
				{
					if (!_text.equals("") && !_text.equals("--"))
					{
//						long value = Long.valueOf(_text);
						long value = Double.valueOf(_text).longValue();
						_text = FormatUtil.longToVolumeHumanReadableFormat(value, m_nDigit);
					}
				}
				catch (Exception e)
				{
					e.printStackTrace();
				}
				break;
			}

			if (m_bAddComma)
			{
				_text = FormatUtil.NumberAddComma(_text);
			}

			if (m_bDollarSign)
			{
				if (m_sDollar != null)
				{
					_text = m_sDollar + " " + _text;
				}
			}

			setText(_text);
		}
		catch (Exception e)
		{

		}
	}
	

	/*
	 * private void enableFdtStyle(boolean enabled) { CharSequence text =
	 * getText(); if (enabled) { Spannable span = new SpannableString(text);
	 * span.setSpan(new RelativeSizeSpan(0.7f), text.length() - 1,
	 * text.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); setText(span); } else
	 * { setText(text); } }
	 * 
	 * private void initFDTfont() { this.setTypeface(this.getTypeface(),
	 * Typeface.BOLD); }
	 * 
	 * public void cancelFDTstyle() { this.setTypeface(this.getTypeface(),
	 * Typeface.NORMAL); this.setTextColor(Color.BLACK); }
	 */
	public void setFieldID(int fieldID)
	{
		m_nFieldID = fieldID;
	}

	public Integer getFieldID()
	{
		return m_nFieldID;
	}

	public void setIOType(IO_TYPE ioType)
	{
		m_enIOType = ioType;
	}

	public IO_TYPE getIOType()
	{
		return m_enIOType;
	}

	public void setSignType(SIGN_TYPE type)
	{
		m_enSignType = type;
	}

	public SIGN_TYPE getSignType()
	{
		return m_enSignType;
	}

	public void setFormat(FORMAT format)
	{
		m_enFormat = format;
	}

	public FORMAT getFdtFormate()
	{
		return m_enFormat;
	}

	public void setDiffColor(boolean flag)
	{
		m_bDiffColor = flag;
	}

	public boolean getDiffColor()
	{
		return m_bDiffColor;
	}

	
	@Override
	protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
		try
		{
			super.onMeasure(widthMeasureSpec, heightMeasureSpec);
		}
		catch (Exception e)
		{
			setMeasuredDimension(widthMeasureSpec, widthMeasureSpec);
		}
	};

	public static void setDiffColor(CustomTextView pView, double pBeforeClose, double pValue)
	{

		Resources res = BaseApp.getApp().getResources();
		if (pBeforeClose == 0.0f)
		{
			pView.setTextColor(res.getColor(R.color.sys_even));
		}
		else
		{
			setDiffColor(pView, pBeforeClose, pValue, res);
		}
	}

	public static void setDiffColor(CustomTextView pView, double pBeforeClose, double pValue, Resources res)
	{
		AppDefine.ColorDef colorDef = null;

		if (pValue > pBeforeClose)
		{
			colorDef = AppDefine.ColorDef.UP;
		}
		else if (pValue < pBeforeClose)
		{
			colorDef = AppDefine.ColorDef.DOWN;
		}
		else
		{
			colorDef = AppDefine.ColorDef.EVEN;
		}

		pView.setTextColor(colorDef.getColor());
	}
		
	@Override
	protected void onDraw(Canvas canvas)
	{
		if (m_bAutoSize)
		{
			String text = getText().toString();
			float tMaxWidth = getWidth() - getCompoundPaddingLeft() - getCompoundPaddingRight();
			float tTextWidth = getPaint().measureText(text);
			float tTextSize = getPaint().getTextSize();

			if (tTextWidth > tMaxWidth)
			{
				TextPaint tPaint = new TextPaint(getPaint());
				tPaint.setTextSize(getPaint().getTextSize());
				float tWidth = tTextWidth;

				while (tWidth > tMaxWidth && tTextSize - 1 >= 1)
				{
					tTextSize = tTextSize - 1;
					tPaint.setTextSize(tTextSize);
					tWidth = tPaint.measureText(text);
				}
				setTextSize(TypedValue.COMPLEX_UNIT_PX, (int) tTextSize);
			}
		}
		super.onDraw(canvas);
	}

	public int getMeasureTextSize(String text)
	{
		int tMaxWidth = (int) (getWidth() - getCompoundPaddingLeft() - getCompoundPaddingRight());
		int tSize = determineMaxTextSize(text, tMaxWidth, getPaint());
		if (m_InitSize > tSize)
		{
			return tSize;
		}
		else
		{
			return m_InitSize;
		}
	}
		
	private int determineMaxTextSize(String text, int maxWidth, TextPaint pTextPaint)
	{
		int tTextSize = m_InitSize;
		TextPaint tPaint = new TextPaint(pTextPaint);
		tPaint.setTextSize(tTextSize);
		float tWidth = tPaint.measureText(text);

		while (tWidth > maxWidth && tTextSize - 1 >= 1)
		{
			tTextSize = tTextSize - 1;
			tPaint.setTextSize(tTextSize);
			tWidth = tPaint.measureText(text);
		}				
		return (int)tPaint.getTextSize();
	}
	
	public void setDiffColorVisibility(boolean pDiffColorVisibility)
	{
		this.m_bDiffColorVisibility = pDiffColorVisibility;
	}

	public DiffSign getSign()
	{
		return m_Sign;
	}
}